use super::*;

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Object {
    pub position: (f32, f32),
    pub angle: f32,
    pub id: String,
    pub name: Option<String>,
}

#[derive(Clone, Serialize, Debug, PartialEq, Deserialize)]
pub struct ObjectTemplate {
    pub list: Vec<Object>,
    pub area: Vec<(f32, f32)>,
    pub lines: Option<Vec<Line>>,
    pub id: Option<String>,
}

impl ObjectTemplate {
    pub fn gen_lines(&mut self) {
        let mut lines = Vec::new();
        for i in 0..self.area.len() {
            for j in i + 1..self.area.len() {
                lines.push(Line::with_turple(self.area[i], self.area[j]));
            }
        }

        self.lines = Some(lines);
    }
    pub fn squre_in(&self, pt: Point, size: f32) -> bool {
        for line in self.lines.as_ref().unwrap().iter() {
            if line.intersect_squre(pt, size) {
                return true;
            }
        }

        false
    }
}

impl MapGen {
    fn can_set_object(&self, (x, y): (usize, usize), object_index: usize) -> bool {
        let (m, n) = self.base_size();

        let nx = y * self.config.block_size + self.config.block_size / 2;
        let ny = x * self.config.block_size + self.config.block_size / 2;

        let mut template = self.templates[object_index].clone();
        for element in template.lines.as_mut().unwrap().iter_mut() {
            element.left.x += nx as f32;
            element.right.x += nx as f32;
            element.left.y += ny as f32;
            element.right.y += ny as f32;
        }

        for j in 0..n {
            for i in 0..m {
                if template.squre_in(
                    Point::new(j as f32, i as f32),
                    self.config.block_size as f32,
                ) {
                    if self.base[i][j].captured != Captured::None {
                        return false;
                    }
                }
            }
        }

        true
    }
    fn set_object(&mut self){
        
    }
    pub fn gen_object(&mut self) -> GenResult<()> {
        let (m, n) = self.base_size();

        let mut err = None;

        for (index, template) in self.templates.iter().enumerate() {
            let mut available = Vec::new();

            for i in 0..m {
                for j in 0..n {
                    if self.can_set_object((i, j), index) {
                        available.push((i, j));
                    }
                }
            }

            if available.len() == 0 {
                err = Some(GenError::NoBlocksSetObject(index));
            }

            let selected = self.rng.gen_range(0..available.len());

        }

        Ok(())
    }
}
